<template>
  <div>
    <!-- 角色列表界面 -->
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <el-button type="primary" @click="addDialog=true">添加角色</el-button>
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',index1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row :class="[index2 === 0 ? '' : 'bdtop','vcenter']" v-for="(item2,index2) in item1.children" :key="item2.id">
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag closable type="warning" v-for="item3 in item2.children" :key="item3.id" @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">修改</el-button>
            <!-- 删除按钮 -->
            <el-button type="warning" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">删除</el-button>
            <!-- 分配权限按钮 -->
            <el-button type="success" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="提示" :visible.sync="addDialog" width="50%" @close="addDialogClosed">
      <!-- 主体部分 -->
      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editDialog" width="50%" @close="editDialogClosed">
      <!-- 主体部分 -->
      <el-form :model="editForm" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加分配角色对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialog" width="50%" @close="setRightDialogClosed">
      <!-- 主体部分 树形控件-->
      <el-tree :data="rightsList" :props="treeProps" ref="treeRef" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
      <!-- 底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name:'Roles',
    data() {
      return {
        //角色列表数据
        rolesList:[],
        //添加角色
        addForm:{
          roleName:'',
          roleDesc:''
        },
        //添加表单的验证规则对象
        addFormRules:{
          //用户名验证
          roleName:[
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ],
          //密码验证
          roleDesc:[
            { required: true, message: '请输入角色描述', trigger: 'blur' }
          ]
        },
        //控制添加角色对话框的显示与隐藏
        addDialog:false,
        //控制修改角色对话框的显示与隐藏
        editDialog:false,
        //查询到的角色对象
        editForm:{},
        //控制分配权限的对话框显示与隐藏
        setRightDialog:false,
        //所有权限的数据
        rightsList:[],
        //树形控件的属性绑定对象
        treeProps:{
          //看到的属性
          label:'authName',
          //父子嵌套属性
          children:'children'
        },
        //默认选中节点的ID值数组
        defKeys:[],
        //当前即将分配权限的角色id
        roleId:''
      }
    },
    created() {
      this.getRolesList()
    },
    methods: {
      //获取角色列表
      async getRolesList() {
        const {data} = await this.$http.get('roles')
        if(data.meta.status !== 200) {
          return this.$message.error('获取角色列表失败')
        }
        this.rolesList = data.data
      },
      //监听添加角色对话框关闭
      addDialogClosed() {
        //重置对话框添加内容(关闭对话框内容重置)
        this.$refs.addFormRef.resetFields()
      },
      //添加角色
      addRole(){
        this.$refs.addFormRef.validate( async vali => {
          if(!vali) return
          const {data} = await this.$http.post('roles',this.addForm)
          if(data.meta.status !== 201) {
            this.$message.error('创建角色失败!')
          }
          this.$message.success('创建角色成功!')
          //隐藏添加用户的对话框
          this.addDialog = false
          //重新刷新用户列表
          this.getRolesList()
        })
      },
      //展示修改角色的对话框
      async showEditDialog(id) {
        const {data} = await this.$http.get('roles/'+id)
        if(data.meta.status !== 200) {
          this.$message.error('获取角色失败')
        }
        //把查询到的角色信息保存到editForm中
        this.editForm = data.data
        //显示修改用户对话框
        this.editDialog = true
      },
      //监听修改用户对话框关闭
      editDialogClosed() {
        //重置内容
        this.$refs.editFormRef.resetFields()
      },
      //修改并提交角色信息
      editRole() {
        this.$refs.editFormRef.validate(async vali =>{
          if(!vali) return
          const {data} = await this.$http.put('roles/'+this.editForm.roleId,{
            roleName:this.editForm.roleName,
            roleDesc:this.editForm.roleDesc
          })
          if(data.meta.status !== 200) {
            return this.$message.error('修改角色失败')
          }
          //关闭对话框
          this.editDialog = false

          this.getRolesList()
          this.$message.success('修改角色成功')
        })
      },
      //删除角色信息
      async removeUserById(id) {
        const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // console.log(res);  确定返回confirm
        if(res !== 'confirm') {
          return this.$message.info('已取消删除')
        }
        const {data} = await this.$http.delete('roles/' + id)
        if(data.meta.status !== 200) {
          return this.$message.error('删除角色失败')
        }
        this.$message.success('删除角色成功')
        this.getRolesList()
      },
      //根据ID删除对应的权限
      async removeRightById(role,rightId) {
        const confirmRes = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(confirmRes !== 'confirm') {
          return this.$message.info('已取消删除该权限')
        }
        const {data} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if(data.meta.status !== 200) {
          return this.$message.error('删除该权限失败')
        }
        this.$message.success('删除该权限成功')
        //给当前角色信息重新赋值一下权限(防止重现刷新整个页面)
        role.children = data.data
      },
      //展示分配权限对话框
      async showSetRightDialog(role) {
        this.roleId = role.id
        //获取所有权限的数据
        const {data} = await this.$http.get('rights/tree')
        if(data.meta.status !== 200) {
          return this.$message.error('获取权限数据失败')
        }
        //把获取到的权限数据保存到data中
        this.rightsList = data.data
        //递归获取三级节点ID(在showSetRightDialog中调用getLeafKeys)
        this.getLeafKeys(role,this.defKeys)
        //显示弹窗
        this.setRightDialog = true
      },
      //定义递归函数获取三级权限的ID,并保存到defKeys数组中
      getLeafKeys(node,arr) {
        //当前node节点不包含children子节点，就是三级权限节点
        if(!node.children) {
          return arr.push(node.id)
        }
        //item为子节点
        node.children.forEach(item => this.getLeafKeys(item,arr))
      },
      //监听分配权限对话框的关闭
      setRightDialogClosed() {
        //对话框关闭的同时清空数组
        this.defKeys = []
      },
      //点击为角色分配权限
      async allotRights() {
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        const {data} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:idStr})
        if(data.meta.status !== 200) {
          return this.$message.error('分配权限失败!')
        }
        this.$message.success('分配权限成功!')
        this.getRolesList()
        this.setRightDialog = false
      }
    },
  }
</script>

<style scoped>
  .el-tag {
    margin: 7px;
  }
  .bdtop {
    border-top: 1px solid #eee;
  }
  .bdbottom {
    border-bottom: 1px solid #eee;
  }
  .vcenter {
    display: flex;
    align-items: center;
  }
</style>